<template>
  <div class="merchant-management-container">
    <!-- 页面标题 -->
<!--    <div class="page-title">租车商家管理</div>-->

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
              v-model="searchForm.username"
              placeholder="请输入登录用户名"
              clearable
          ></el-input>
        </el-col>
        <el-col :span="6">
          <el-input
              v-model="searchForm.merchantName"
              placeholder="请输入商家名称"
              clearable
          ></el-input>
        </el-col>
        <el-col :span="6">
          <el-input
              v-model="searchForm.address"
              placeholder="请输入商家地址"
              clearable
          ></el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetForm" style="margin-left: 10px;">重置</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 卡片列表区域 -->
    <div class="card-list-container">
      <el-skeleton :loading="loading" row="5" :columns="3" animated>
        <el-card
            class="merchant-card"
            v-for="(item, index) in tableData"
            :key="index"
        >
          <div class="card-header">
            <!-- 商家Logo和基本信息 -->
            <div class="logo-container">
              <el-image
                  :src=   "`/api/file/download.do?filename=${item.logoUrl}`"
                  :alt="item.merchantName || 'Logo'"
                  class="merchant-logo"
                  fallback-src="https://cube.elemecdn.com/e/fd/0fc7d205a967d26456f5871db373.jpe"
              ></el-image>
            </div>

            <div class="basic-info">
              <div class="merchant-name">
                {{ item.merchantName || '--' }}
                <el-tag
                    :type="item.status === 1 ? 'success' : 'danger'"
                    class="status-tag"
                >
                  {{ item.status === 1 ? '正常' : '禁用' }}
                </el-tag>
              </div>
              <div class="merchant-id">ID: {{ item.id || '--' }}</div>
              <div class="contact-info">
                <span>联系人: {{ item.contactPerson || '--' }}</span>
                <span>电话: {{ item.contactPhone || '--' }}</span>
              </div>
            </div>
          </div>

          <div class="card-body">
            <div class="info-row">
              <span class="label">登录用户名:</span>
              <span class="value">{{ item.username || '--' }}</span>
            </div>
            <div class="info-row">
              <span class="label">商家地址:</span>
              <span class="value">{{ item.address || '--' }}</span>
            </div>
          </div>

          <div class="card-actions">
            <el-button
                size="small"
                type="primary"
                @click="handleDetail(item)"
            >
              详情
            </el-button>
            <el-button
                size="small"
                :type="item.status === 1 ? 'danger' : 'success'"
                @click="item.status === 1 ? handleForbid(item.id) : handleActivate(item.id)"
            >
              {{ item.status === 1 ? '禁用' : '激活' }}
            </el-button>
          </div>
        </el-card>
      </el-skeleton>
    </div>

    <!-- 空状态提示 -->
    <div v-if="!loading && tableData.length === 0" class="empty-state">
      <el-empty description="暂无商家数据"></el-empty>
    </div>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNo"
          :page-sizes="[6, 12, 24, 48]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      ></el-pagination>
    </div>

    <!-- 详情模态框 -->
    <el-dialog
        title="商家详情"
        v-model="detailDialogVisible"
        width="60%"
        :close-on-click-modal="false"
    >
      <el-descriptions column="1" border>
        <el-descriptions-item label="商家ID">{{ currentRow?.id || '--' }}</el-descriptions-item>
        <el-descriptions-item label="登录用户名">{{ currentRow?.username || '--' }}</el-descriptions-item>
        <el-descriptions-item label="登录密码">{{ currentRow?.password || '--' }}</el-descriptions-item>
        <el-descriptions-item label="商家名称">{{ currentRow?.merchantName || '--' }}</el-descriptions-item>
        <el-descriptions-item label="联系人">{{ currentRow?.contactPerson || '--' }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ currentRow?.contactPhone || '--' }}</el-descriptions-item>
        <el-descriptions-item label="商家地址">{{ currentRow?.address || '--' }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag
              :type="currentRow?.status === 1 ? 'success' : 'danger'"
          >
            {{ currentRow?.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="商家Logo">
          <el-image
              :src="`/api/file/download.do?filename=${currentRow?.logoUrl}`"
              :alt="currentRow?.merchantName || 'Logo'"
              style="width: 150px; height: 150px; object-fit: contain;"
              fallback-src="https://cube.elemecdn.com/e/fd/0fc7d205a967d26456f5871db373.jpe"
          ></el-image>
        </el-descriptions-item>
        <el-descriptions-item label="营业执照">
          <el-image
              :src="`/api/file/download.do?filename=${currentRow?.businessLicense}`"
              alt="营业执照"
              style="width: 150px; height: 150px; object-fit: contain;"
              fallback-src="https://cube.elemecdn.com/e/fd/0fc7d205a967d26456f5871db373.jpe"
          ></el-image>
        </el-descriptions-item>
        <el-descriptions-item label="商家描述" label-class-name="description-label">
          <pre style="white-space: pre-wrap; word-wrap: break-word; margin: 0;">{{ currentRow?.description  }}</pre>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElDialog, ElDescriptions, ElDescriptionsItem, ElImage, ElSkeleton, ElEmpty } from 'element-plus'
import axios from 'axios'
import { activeAdmin, forbidAdmin, getAdminList } from "@/api/AdminMerchant";

// 搜索表单数据
const searchForm = ref({
  username: '',
  merchantName: '',
  address: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const pageNo = ref(1)
const pageSize = ref(6)

// 详情模态框相关
const detailDialogVisible = ref(false)
const currentRow = ref(null)

// 页面加载时获取数据
onMounted(() => {
  fetchMerchants()
})

// 获取商家列表
const fetchMerchants = async () => {
  loading.value = true
  try {
    const response = await getAdminList({
      pageNo: pageNo.value,
      pageSize: pageSize.value,
      username: searchForm.value.username,
      merchantName: searchForm.value.merchantName,
      address: searchForm.value.address
    })

    if (response.code === 200) {
      tableData.value = response.data.records || []
      total.value = response.data.count || 0
    } else {
      ElMessage.error(response.message || '获取商家列表失败')
    }
  } catch (error) {
    ElMessage.error('网络错误，获取商家列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 查看详情
const handleDetail = (row) => {
  currentRow.value = { ...row }
  detailDialogVisible.value = true
}

// 禁用商家
const handleForbid = async (id) => {
  ElMessageBox.confirm(
      '确定要禁用该商家吗？禁用后商家将无法正常营业',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }
  ).then(async () => {
    try {
      const response = await forbidAdmin({ id })
      if (response.code === 200&&response.success=== true) {
        ElMessage.success('禁用成功')
        fetchMerchants()
      } else {
        ElMessage.error(response.message || '禁用失败')
      }
    } catch (error) {
      ElMessage.error('网络错误，禁用失败')
      console.error(error)
    }
  }).catch(() => {})
}

// 激活商家
const handleActivate = async (id) => {
  ElMessageBox.confirm(
      '确定要激活该商家吗？激活后商家可正常营业',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success'
      }
  ).then(async () => {
    try {
      const response = await activeAdmin({ id })
      if (response.code === 200&&response.success=== true) {
        ElMessage.success('激活成功')
        fetchMerchants()
      } else {
        ElMessage.error(response.message || '激活失败')
      }
    } catch (error) {
      ElMessage.error('网络错误，激活失败')
      console.error(error)
    }
  }).catch(() => {})
}

// 搜索、分页等辅助方法
const handleSearch = () => {
  pageNo.value = 1
  fetchMerchants()
}

const resetForm = () => {
  searchForm.value = {
    username: '',
    merchantName: '',
    address: ''
  }
  pageNo.value = 1
  fetchMerchants()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchMerchants()
}

const handleCurrentChange = (val) => {
  pageNo.value = val
  fetchMerchants()
}
</script>

<style scoped>
.merchant-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-title {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
}

.search-card {
  background-color: #fff;
  padding: 15px;
  margin-bottom: 20px;
}

/* 卡片列表样式 */
.card-list-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.merchant-card {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  transition: transform 0.2s, box-shadow 0.2s;
}

.merchant-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  padding: 15px 15px 10px;
  border-bottom: 1px dashed #eee;
}

.logo-container {
  flex-shrink: 0;
  margin-right: 15px;
}

.merchant-logo {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  object-fit: contain;
}

.basic-info {
  flex-grow: 1;
}

.merchant-name {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.status-tag {
  margin-left: 10px;
}

.merchant-id {
  color: #666;
  font-size: 13px;
  margin-bottom: 10px;
}

.contact-info {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  font-size: 14px;
  color: #666;
}

.card-body {
  padding: 15px;
  flex-grow: 1;
}

.info-row {
  display: flex;
  margin-bottom: 8px;
  font-size: 14px;
}

.label {
  color: #888;
  width: 100px;
  flex-shrink: 0;
}

.value {
  color: #333;
  word-break: break-all;
}

.card-actions {
  display: flex;
  justify-content: flex-end;
  padding: 10px 15px;
  border-top: 1px dashed #eee;
  gap: 10px;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 50px 0;
}

/* 分页样式 */
.pagination-container {
  text-align: right;
  margin-top: 20px;
}

/* 详情页样式 */
:deep(.el-descriptions) {
  margin-top: 10px;
}

:deep(.description-label) {
  vertical-align: top !important;
  padding-top: 12px !important;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .card-list-container {
    grid-template-columns: 1fr;
  }

  .card-header {
    flex-direction: column;
    align-items: center;
  }

  .logo-container {
    margin-right: 0;
    margin-bottom: 15px;
  }

  .basic-info {
    width: 100%;
    text-align: center;
  }

  .merchant-name {
    justify-content: center;
  }
}
</style>